package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.ApplicationInfo;
import com.leyou.auth.mapper.ApplicationInfoMapper;
import com.leyou.common.auth.pojo.AppInfo;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ApplicationInfoMapper applicationInfoMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    public void login(String username, String password, HttpServletRequest request, HttpServletResponse response) {
        //校验用户名和密码是否正确
        User user = null;
        try {
            user = userClient.findUser(username, password);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //将User对象转成UserInfo
        UserInfo userInfo = new UserInfo(user.getId(), user.getUsername(), "admin");
        createTokenToCookie(request, response, userInfo);
    }

    /**
     * 生成token并写入浏览器
     */
    public void createTokenToCookie(HttpServletRequest request, HttpServletResponse response, UserInfo userInfo) {
        //生成jwt的token
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getCookie().getExpire());
        //将token写入浏览器的cookie中
        CookieUtils.newCookieBuilder()
                .request(request)
                .response(response)
                .httpOnly(true)
                .domain(jwtProperties.getCookie().getCookieDomain())
                .name(jwtProperties.getCookie().getCookieName())
                .value(token)
                .build();
    }

    public UserInfo clientVerify(HttpServletRequest request, HttpServletResponse response) {
        //获取token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookie().getCookieName());
        //判空
        if(StringUtils.isEmpty(token)){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        Payload<UserInfo> payload = null;
        //解析
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey(), UserInfo.class);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //获取token的id
        String tokenId = payload.getId();
        //判断当前token的id是否在黑名单
        if(redisTemplate.hasKey(tokenId)){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //获取用户信息
        UserInfo userInfo = payload.getUserInfo();
        //获取过期时间
        Date expDate = payload.getExpiration();
        //获取刷新时间点
        DateTime refreshTime = new DateTime(expDate).minusMinutes(jwtProperties.getCookie().getRefreshTime());
        //如果当前时间在刷新时间点之后刷新
        if(refreshTime.isBeforeNow()){
            createTokenToCookie(request, response, userInfo);
        }
        return userInfo;
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //获取token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookie().getCookieName());
        //判空
        if(StringUtils.isEmpty(token)){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        Payload<UserInfo> payload = null;
        //解析
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey(), UserInfo.class);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //获取token的有效剩余时间
        long remainTime = payload.getExpiration().getTime() - System.currentTimeMillis();
        //如果过期时间超过1秒放入redis中
        if(remainTime>1000){
            redisTemplate.opsForValue().set(payload.getId(), "随便写", remainTime, TimeUnit.MILLISECONDS);
        }
        //删除token
        CookieUtils.deleteCookie(jwtProperties.getCookie().getCookieName(),
                jwtProperties.getCookie().getCookieDomain(), response);
    }

    /**
     * 校验服务id和服务密钥是否正确的方法
     */
    public Boolean isUsable(Long id, String serviceName){
        //先根据服务id查询服务信息
        ApplicationInfo applicationInfo = applicationInfoMapper.selectById(id);
        if(applicationInfo==null){
            return false;
        }
        //校验密钥是否正确
        if(!passwordEncoder.matches(serviceName, applicationInfo.getSecret())){
            return false;
        }
        return true;
    }

    public String authorize(Long id, String serviceName) {
        //校验服务器的id和密钥是否可用
        if(!isUsable(id, serviceName)){
            log.error("【服务器申请token】异常！服务id或者服务名称不正确!");
            throw new LyException(ExceptionEnum.INVALID_SERVER_ID_SECRET);
        }
        //获取来访服务可以访问的服务器列表
        List<Long> targetIds = applicationInfoMapper.queryTargetIdList(id);
        //创建生成token的app对象
        AppInfo appInfo = new AppInfo(id, serviceName, targetIds);
        //生成token
        String token = JwtUtils.generateTokenExpireInMinutes(appInfo, jwtProperties.getPrivateKey(), jwtProperties.getApp().getExpire());
        return token;
    }

}
